package com.tian.common.intercptor;

import com.tian.common.exception.BusinessException;
import com.tian.common.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-03-11 11:28
 * {@code @version:} 1.0
 */
@Order(0)
@Aspect
@Component
@PropertySource(value = "classpath:login-filter.properties")
public class AuthAspect {
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Value("#{'${ignoreLoginUrls}'.split(',')}")
    private List<String> ignoreLoginUrls;

    @Pointcut("execution(* com.tian.controller..*.*(..))")
    public void controllerPointcut() {}

    @Around("controllerPointcut()")
    public Object checkAuth(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.currentRequestAttributes()).getRequest();
        String requestUri = request.getRequestURI();
        // 白名单校验
        for (String pattern : ignoreLoginUrls) {
            if (pathMatcher.match(pattern, requestUri)) {
                return joinPoint.proceed();
            }
        }
        if(requestUri.startsWith("/management")||requestUri.contains("/management")||requestUri.contains("/city")){
            return joinPoint.proceed();
        }

        // 登录校验逻辑（示例）
        String authorization =  request.getHeader("Authorization");
        if (StringUtil.isBlank(authorization)) {
            throw new BusinessException("请先登录");
        }

        return joinPoint.proceed();
    }
}
